import feedparser
import urllib
from sgmllib import SGMLParser
import time
import os
import os.path

"""get image form yahoo gallery
   platform: linux, windows
"""
__imgbase__ = '/home/nevup/Pictures/hou'

#http://sports.yahoo.com/nba/teams/hou/photos/rss.xml
class ImgLister(SGMLParser):
    def reset(self):
        SGMLParser.reset(self)
        self.urls = []
    def start_img(self, attrs):
        src = [v for k, v in attrs if k == 'src']
        if src:
            self.urls.extend(src)

def getRss(url):
    d = feedparser.parse(url)
    return d;

if __name__ == '__main__':
    hou_rss = 'http://sports.yahoo.com/nba/teams/hou/photos/rss.xml'
    pic_home = __imgbase__
    d = getRss(hou_rss)
    parser = ImgLister()
    for entry in d['entries']:
        date = entry['updated_parsed']
        folder_name = time.strftime("%y-%m-%d",date) 
        htmllet = entry['summary_detail']['value']
        parser.reset()
        parser.feed(htmllet)
        for src in parser.urls:
            src = src.replace('thumbe', 'fullj', 1)
            src = src.replace("thumb", 'capt', 1)
            fn = src[src.rindex('.', 1, src.rindex('.', 1))+1:]
            idx = fn.rfind('-', 1)
            if (idx != -1):
                fn = fn[idx+1:]

            dir_name = pic_home + '/' + folder_name
            if (not os.path.exists(dir_name)):
                os.makedirs(dir_name)
            abs_name = dir_name + '/' + fn
            if (not os.path.exists(abs_name)):
                sock = urllib.urlopen(src)
                bin_img = sock.read()
                sock.close()
                f = open(dir_name+'/'+fn ,"wb")
                f.write(bin_img)
                f.close()
                print '[Create] ',abs_name
            else:
                print '[Skip] ',abs_name

    parser.close()

